package com.unicom.office;

import com.unicom.office.builder.OfficeBuilder;
import com.unicom.office.config.OfficeConfig;
import com.unicom.office.dataitem.DataItem;
import com.unicom.office.func.FuncBase;
import com.unicom.office.runtime.OfficeRuntime;
import com.unicom.office.parser.OfficeParser;
import com.unicom.office.unit.OfficeUnit;
import com.unicom.office.unit.RootUnit;
import com.unicom.office.util.FileUtil;

import java.util.List;
import java.util.Map;

public class OfficeRenderHelper {
    private OfficeParser officeParser;
    private OfficeBuilder officeBuilder;
    private OfficeRuntime officeRuntime;
    private FuncBase template;
    private OfficeConfig officeConfig;

    public OfficeRenderHelper(String templatePath, OfficeConfig config, OfficeRuntime runtime){
        this.officeConfig = config;
        officeRuntime = runtime;

        String ext = FileUtil.getExtension(templatePath);
        officeParser = OfficeHelper.getDefaultParser(ext);
        officeParser.setConfig(officeConfig);
        officeParser.setRuntime(runtime);

        template = officeParser.parse(templatePath);
    }

    public void setParser(OfficeParser officeParser){
        officeParser.setConfig(officeConfig);
        officeParser.setRuntime(officeRuntime);
        this.officeParser = officeParser;
    }

    public OfficeRenderHelper setBulider(OfficeBuilder officeBuilder){
        officeBuilder.setConfig(officeConfig);
        officeBuilder.setRuntime(officeRuntime);
        this.officeBuilder = officeBuilder;
        return this;
    }

    public void render(Map<String, Object> data, String targetPath){
        String ext = FileUtil.getExtension(targetPath);
        if(officeBuilder == null) {
            officeBuilder = OfficeHelper.getDefaultBuilder(ext);
            officeBuilder.setConfig(officeConfig);
            officeBuilder.setRuntime(this.officeRuntime);
        }

        officeRuntime.in(data, officeConfig);
        Object result = template.run(officeRuntime);
        if(result instanceof List){
            officeBuilder.build((List<OfficeUnit>)result, targetPath);
        }else {
            officeBuilder.build((RootUnit) result, targetPath);
        }
    }
}
